package shoppingmall.manage.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import shoppingmall.manage.dto.LoginRequestParamsVO;
import shoppingmall.manage.dto.Result;
import shoppingmall.manage.pojo.AdminUser;

import shoppingmall.manage.service.AdministratorService;
import shoppingmall.manage.utils.JwtUtils;

import java.util.HashMap;
import java.util.Map;

@Slf4j  //记录日志
@RestController
public class LoginController {

    @Autowired(required = false)
    private AdministratorService administratorService;

    /**
     * 后台管理员用户登录
     * @param user
     * @return
     */
    @PostMapping("/manage/login")
    public Result login (@RequestBody LoginRequestParamsVO user, HttpServletRequest request) {
        log.info("管理员登录,用户名={},密码={},验证码={}",user.getUsername(),user.getPassword(),user.getCaptchaCode());

        //从会话中获取图片验证码
        String captchaImgCode = request.getSession().getAttribute("captchaCode").toString();
        if(!captchaImgCode.toLowerCase().equals(user.getCaptchaCode().toLowerCase())) {
            return Result.error("验证码错误!");
        }

        //查询用户信息
        AdminUser u = administratorService.login(user);
        //登录成功，生成令牌，下发令牌
        if(u != null){
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",u.getId());
            claims.put("username",u.getUsername());
            String jwt = JwtUtils.generateJwt(claims);  //jwt当中包含了管理员的登录信息
            return Result.success(jwt);
        }

        //登录失败，返回错误信息
        return Result.error("用户名或密码错误!");
    }

}
